package cn.newhopedairy.gateway.component;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 从Nacos注册中心获取分布式微服务的Swagger API资源
 *
 * @author Neo.Li
 * @date 2020-10-0310:32
 */
@Primary
@Component
public class SwaggerProvider implements SwaggerResourcesProvider {

    /**
     * swagger3默认的url后缀
     */
    private static final String SWAGGER2URL = "/v3/api-docs";

    /**
     * 网关路由
     */
    @Autowired
    private RouteLocator routeLocator;

    /**
     * 网关名称
     */
    @Value("${spring.application.name}")
    private String name;

    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resources = new ArrayList<>();
        Set<String> hosts = new HashSet<>();
        // 获取所有注册服务的名称
        routeLocator.getRoutes().filter(route -> route.getUri().getHost() != null)
                .filter(route -> !name.equals(route.getUri().getHost()))
                .subscribe(route -> {
                    String host = route.getUri().getHost();
                    if(!hosts.contains(host)) {
                        hosts.add(host);
                    }
                });
        // 记录已经添加过的server，存在同一个应用注册了多个服务在nacos上
        hosts.forEach(routeHost -> {
            String url = "/" + routeHost + SWAGGER2URL;
            SwaggerResource swaggerResource = new SwaggerResource();
            swaggerResource.setName(routeHost);
            swaggerResource.setUrl(url);
            resources.add(swaggerResource);
        });

        return resources;
    }
}
